package com.itqian.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itqian.common.exception.Assert;
import com.itqian.common.exception.ResponseEnum;
import com.itqian.common.utils.ResultVOUtil;
import com.itqian.common.vo.ResultVO;
import com.itqian.user.entity.UserAddress;
import com.itqian.user.service.UserAddressService;
import com.itqian.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author shishuqian
 * date 2022/4/10
 * time 20:56
 **/
@RestController
@RequestMapping("/user/address")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService;

    /**
     *  查询用户的所有送货地址
     */
    @GetMapping("/list")
    public ResultVO list(@RequestHeader("token") String token){
        //获取用户id
        Integer userId = TokenUtils.getUserId(token);
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<UserAddress> list = userAddressService.list(wrapper);
        return ResultVOUtil.success(list);
    }

    /**
     *  添加用户的送货地址
     */
    @PostMapping("/add")
    public ResultVO add(@RequestHeader("token") String token, @Valid @RequestBody UserAddress address){
        //获取用户id
        Integer userId = TokenUtils.getUserId(token);
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(address,userAddress);
        userAddress.setUserId(userId);
        boolean save = userAddressService.save(userAddress);
        return ResultVOUtil.success(null);
    }

    /**
     *  修改用户的送货地址
     */
    @PutMapping("/update")
    public ResultVO update(@RequestHeader("token") String token, @Valid @RequestBody UserAddress address){
        //获取用户id
        Integer userId = TokenUtils.getUserId(token);
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(address,userAddress);
        userAddress.setUserId(userId);
        boolean b = userAddressService.updateById(userAddress);
        return ResultVOUtil.success(null);
    }

    /**
     *  删除用户的所有送货地址
     */
    @DeleteMapping("/delete/{id}")
    public ResultVO delete(@PathVariable Integer id){
        Assert.notNull(id, ResponseEnum.PARAM_NOTNULL);

        boolean b = userAddressService.removeById(id);
        return ResultVOUtil.success(null);

    }


}
